#!/bin/bash
set -eo pipefail

dt='{{ execution_date | date_add(-5 + 1) | cst_ds }}'
name='始发出港时长'

# 在退出时清理文件
trap "rm -f /tmp/${name}_${dt}.zip /tmp/${name}_${dt}.csv && echo 'removed tmp files'" EXIT

# 生成带有 UTF8 BOM 的 csv 文件
{
  echo -ne "\xEF\xBB\xBF";
  beeline -nhdp_hive_admin -pnd8VsiluE6 \
  --outputformat=csv2 \
  --showHeader=true \
  -e "
  SELECT taking_time_period                               AS \`揽收时间段\`,
         waybill_cnt                                      AS \`票数\`,
         subordinate_agent_name                           AS \`揽收点代理区名称\`,
         subordinate_agent_code                           AS \`揽收点代理区编码\`,
         taking_network_name                              AS \`网点名称\`,
         taking_network_code                              AS \`网点编号\`,
         entrepot_network_name                            AS \`集散名称\`,
         entrepot_network_code                            AS \`集散编号\`,
         center_network_name                              AS \`中心名称\`,
         center_network_code                              AS \`中心编号\`,
         sum_taking_entrepot_dur                          AS \`网点-集散时长总和（小时）\`,
         sum_entrepot_arrival_send_dur                    AS \`集散到-发时长总和（小时）\`,
         sum_entrepot_center_dur                          AS \`集散-中心时长总和（小时）\`,
         sum_taking_center_dur                            AS \`网点-中心时长总和（小时）\`,
         sum_taking_entrepot_trans_dur                    AS \`网点-集散运输时长总和（小时）\`,
         sum_entrepot_center_trans_dur                    AS \`集散-首中心运输时长总和（小时）\`,
         sum_taking_center_trans_dur                      AS \`网点-首中心运输时长总和（小时）\`,
         sum_taking_entrepot_dur / nullif(waybill_cnt, 0) AS \`网点-集散的平均时长（小时）\`,
         sum_entrepot_center_dur / nullif(waybill_cnt, 0) AS \`集散-首中心平均时长（小时）\`,
         sum_taking_center_dur / nullif(waybill_cnt, 0)   AS \`网点-首中心平均时长（小时）\`,
         dt                                               AS \`揽件日期\`
    FROM jms_dm.dm_collect_duration_dt
   WHERE dt = '$dt';
"
} > /tmp/${name}_${dt}.csv

# 压缩并删除 csv 文件
zip -jrm /tmp/${name}_${dt}.zip /tmp/${name}_${dt}.csv

# 上传文件
/usr/local/python3/bin/python3 /usr/local/airflow/dags/utils/operators/upload_oss.py  ${name}/${name}_${dt}.zip /tmp/${name}_${dt}.zip

# zip 文件将在进程退出后被自动清理
